package com.tom.architect.party3.day31;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public abstract class Schedulers {
    static Schedulers MAIN_THREAD;
    static Schedulers IO;

    static { // 单例。
        IO = new IOSchedulers();
        MAIN_THREAD = new MainSchedulers(new Handler(Looper.getMainLooper()));
    }

    public static Schedulers io() {
        return IO;
    }

    public abstract void scheduleDirect(Runnable schedulerTask);

    public static Schedulers mainThread() {
        return MAIN_THREAD;
    }

    // IO线程
    private static class IOSchedulers extends Schedulers {
        ExecutorService service; // 构建线程池, 使用系统的线程池

        public IOSchedulers() {
            service = Executors.newScheduledThreadPool(1, new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "子线程IOSchedulers"); // 子线程有名称 子线程IOSchedulers
                }
            });
        }

        @Override
        public void scheduleDirect(Runnable runnable) {
            service.submit(runnable); // 加入队列中执行
        }
    }

    // 内部类。UI线程。
    private static class MainSchedulers extends Schedulers {
        Handler handler;
        public MainSchedulers(Handler handler) {
            this.handler = handler;
        }

        @Override
        public void scheduleDirect(Runnable runnable) {
            // 享元设计模式，传递了callback不需要复写handleMessage方法。
            Message message = Message.obtain(handler, runnable);
            handler.sendMessage(message);
        }
    }

}
